<template>
    <div class="user-detail-page">
        <!-- 顶部导航栏 -->
        <HeaderNav active-menu="network" />

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 左侧边栏 -->
            <Sidebar :active-sidebar="activeSidebar" @sidebar-select="handleSidebarSelect" />

            <!-- 右侧内容区域 -->
            <main class="user-detail-main">
                <div class="user-detail-container">
                    <!-- 用户基本信息卡片 -->
                    <el-card class="user-profile-card">
                        <div class="profile-header">
                            <div class="avatar-section">
                                <div class="user-avatar">
                                    <img :src="userInfo.avatar || '/default-avatar.png'" alt="头像" />
                                </div>
                                <div class="avatar-actions">
                                    <el-button v-if="!isOwnProfile && !isFollowing" type="primary" @click="handleFollow"
                                        :loading="followLoading">
                                        关注
                                    </el-button>
                                    <el-button v-if="!isOwnProfile && isFollowing" @click="handleUnfollow"
                                        :loading="followLoading">
                                        已关注
                                    </el-button>
                                    <el-button v-if="!isOwnProfile" type="success" @click="handleSendMessage">
                                        发消息
                                    </el-button>
                                </div>
                            </div>

                            <div class="profile-info">
                                <h1 class="username">{{ displayName }}</h1>
                                <div class="user-meta">
                                    <span v-if="userInfo.position" class="position">
                                        <el-icon>
                                            <Briefcase />
                                        </el-icon>
                                        {{ userInfo.position }}
                                    </span>
                                    <span v-if="userInfo.city" class="city">
                                        <el-icon>
                                            <Location />
                                        </el-icon>
                                        {{ userInfo.city }}
                                    </span>
                                </div>
                                <p v-if="userInfo.bio" class="bio">{{ userInfo.bio }}</p>

                                <div class="profile-stats">
                                    <div class="stat-item" @click="goToFollowList('following')">
                                        <span class="stat-number">{{ stats.following || 0 }}</span>
                                        <span class="stat-label">关注</span>
                                    </div>
                                    <div class="stat-item" @click="goToFollowList('followers')">
                                        <span class="stat-number">{{ stats.followers || 0 }}</span>
                                        <span class="stat-label">粉丝</span>
                                    </div>
                                    <div class="stat-item">
                                        <span class="stat-number">{{ stats.posts || 0 }}</span>
                                        <span class="stat-label">动态</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 用户详细信息 -->
                        <div class="profile-details">
                            <el-descriptions :column="2" border>
                                <el-descriptions-item label="邮箱">{{ userInfo.email || '未知' }}</el-descriptions-item>
                                <el-descriptions-item label="电话">{{ userInfo.phone || '未知' }}</el-descriptions-item>
                                <el-descriptions-item label="年级">{{ userInfo.grade || '未知' }}</el-descriptions-item>
                                <el-descriptions-item label="专业">{{ userInfo.major || '未知' }}</el-descriptions-item>
                                <el-descriptions-item label="公司">{{ userInfo.company || '未知' }}</el-descriptions-item>
                                <el-descriptions-item label="职位">{{ userInfo.position || '未知' }}</el-descriptions-item>
                                <el-descriptions-item label="所在城市">{{ userInfo.city || '未知' }}</el-descriptions-item>
                                <el-descriptions-item label="注册时间">
                                    {{ userInfo.verification_status === 0 ? '未认证' : '已认证' }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </div>
                    </el-card>

                    <!-- 用户动态 -->
                    <el-card class="user-posts-card" v-if="posts.length > 0">
                        <template #header>
                            <div class="card-header">
                                <span>最新动态</span>
                            </div>
                        </template>
                        <div class="posts-list">
                            <div v-for="post in posts" :key="post.post_id" class="post-item">
                                <div class="post-content">
                                    {{ post.content }}
                                </div>

                                <!-- 动态图片展示 -->
                                <div v-if="post.images && post.images.length > 0" class="post-images">
                                    <div class="images-grid" :class="`images-${Math.min(post.images.length, 4)}`">
                                        <div v-for="(image, index) in post.images" :key="index" class="image-item"
                                            @click="viewImage(post.images, index)">
                                            <img :src="image" :alt="`图片${index + 1}`" />
                                        </div>
                                    </div>
                                </div>

                                <div class="post-meta">
                                    <span class="post-time">{{ formatTime(post.created_at) }}</span>
                                    <span class="post-stats">
                                        <el-icon>
                                            <ChatDotRound />
                                        </el-icon> {{ post.comment_count || 0 }}
                                        <el-icon>
                                            <Star />
                                        </el-icon> {{ post.like_count || 0 }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </el-card>

                    <!-- 空状态 -->
                    <el-card v-else class="empty-posts">
                        <el-empty description="该用户暂无动态" />
                    </el-card>
                </div>
            </main>
        </div>

        <!-- 图片预览对话框 -->
        <el-dialog v-model="imagePreviewVisible" :fullscreen="true" @close="closeImagePreview">
            <div class="image-preview">
                <el-carousel ref="carouselRef" :initial-index="previewImageIndex" indicator-position="outside"
                    class="preview-carousel">
                    <el-carousel-item v-for="(image, index) in previewImages" :key="index">
                        <div class="carousel-image">
                            <img :src="image" :alt="`图片${index + 1}`" />
                        </div>
                    </el-carousel-item>
                </el-carousel>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElCarousel, ElCarouselItem, ElDialog } from 'element-plus'
import { View, ChatDotRound, Star, Briefcase, Location } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useFollowsStore } from '@/stores/follow'
import { usePostsStore } from '@/stores/posts'
import HeaderNav from '@/components/layout/HeaderNav.vue'
import Sidebar from '@/components/layout/Sidebar.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const followsStore = useFollowsStore()
const postsStore = usePostsStore()

const userInfo = ref({})
const posts = ref([])
const followLoading = ref(false)
const isFollowing = ref(false)
const activeSidebar = ref('network')

// 统计数据
const stats = ref({
    following: 0,
    followers: 0,
    posts: 0
})

// 图片预览相关
const imagePreviewVisible = ref(false)
const previewImages = ref([])
const previewImageIndex = ref(0)
const carouselRef = ref(null)

const userId = computed(() => route.params.userId)
const isOwnProfile = computed(() => {
    return userStore.userInfo?.user_id === userId.value
})
const displayName = computed(() => {
    return userInfo.value.nickname || userInfo.value.email || '未知用户'
})

// 侧边栏导航
const handleSidebarSelect = (index) => {
    activeSidebar.value = index
    switch (index) {
        case 'dashboard':
            router.push('/')
            break
        case 'social':
            router.push('/social')
            break
        case 'circles':
            router.push('/circle')
            break
        case 'chat':
            router.push('/chat')
            break
        case 'lost-found':
            router.push('/lost-and-found')
            break
        case 'second-hand':
            router.push('/second-hand')
            break
        case 'recruitment':
            router.push('/recruitment')
            break
        default:
            ElMessage.success(`当前已是在 ${index}页面`)
    }
}

// 获取用户详情
const fetchUserDetail = async () => {
    try {
        const response = await userStore.getUserByIdAction(userId.value)
        if (response.code === 0) {
            userInfo.value = response.data
            // 先加载统计数据
            await loadStats()
            // 再检查关注状态
            await checkFollowStatus()
        } else {
            ElMessage.error(response.msg || '获取用户信息失败')
        }
    } catch (error) {
        ElMessage.error('获取用户信息失败')
        console.error(error)
    }
}

// 加载统计数据 - 参考UserStatsCard.vue的实现
const loadStats = async () => {
    try {
        // 获取关注列表统计
        const followingResult = await followsStore.fetchFollowingList(userId.value, { page: 1, pageSize: 1 })
        if (followingResult.code === 0) {
            stats.value.following = followingResult.data.pagination?.total || 0
        } else {
            console.error('获取关注数失败:', followingResult.msg)
        }

        // 获取粉丝列表统计
        const followersResult = await followsStore.fetchFollowersList(userId.value, { page: 1, pageSize: 1 })
        if (followersResult.code === 0) {
            stats.value.followers = followersResult.data.pagination?.total || 0
        } else {
            console.error('获取粉丝数失败:', followersResult.msg)
        }

        // 获取动态数量
        stats.value.posts = posts.value.length

        console.log('统计数据:', stats.value) // 调试用
    } catch (error) {
        console.error('加载统计数据失败:', error)
    }
}

// 检查关注状态 - 参考UserCard.vue的实现
const checkFollowStatus = async () => {
    if (isOwnProfile.value) return

    try {
        const result = await followsStore.fetchFollowingList(userStore.getUserId(), {
            page: 1,
            pageSize: 1000
        })

        if (result.code === 0) {
            const followingList = result.data.list || []
            const isUserFollowed = followingList.some(item =>
                String(item.follow_id) === userId.value ||
                item.user?.user_id === userId.value
            )
            isFollowing.value = isUserFollowed
        }
    } catch (error) {
        console.error('检查关注状态失败:', error)
    }
}

// 获取用户动态
const fetchUserPosts = async () => {
    try {
        const response = await postsStore.fetchUserPosts(userId.value)
        if (response.code === 0) {
            let rawPosts = response.data.list || response.data || []
            // 处理图片字段：将逗号分隔的字符串转换为数组
            posts.value = rawPosts.map(post => {
                // 检查images是否为字符串且包含逗号分隔的URL
                if (typeof post.images === 'string' && post.images) {
                    // 将逗号分隔的字符串转换为数组
                    post.images = post.images.split(',').map(url => url.trim())
                } else if (!Array.isArray(post.images)) {
                    // 如果不是字符串也不是数组，则设为空数组
                    post.images = []
                }
                return post
            })
            // 更新动态数量
            stats.value.posts = posts.value.length
            console.log('用户动态:', posts.value)
        }
    } catch (error) {
        console.error('获取用户动态失败:', error)
    }
}

// 关注用户
const handleFollow = async () => {
    if (followLoading.value) return

    try {
        followLoading.value = true
        await followsStore.followUserAction(userId.value)
        isFollowing.value = true
        // 重新加载统计数据
        await loadStats()
        ElMessage.success('关注成功')

        window.dispatchEvent(new CustomEvent('followStatusChanged'))
    } catch (error) {
        ElMessage.error(error.message || '关注失败')
    } finally {
        followLoading.value = false
    }
}

// 取消关注
const handleUnfollow = async () => {
    if (followLoading.value) return

    try {
        followLoading.value = true
        await followsStore.unfollowUserAction(userId.value)
        isFollowing.value = false
        // 重新加载统计数据
        await loadStats()
        ElMessage.success('取消关注成功')

        window.dispatchEvent(new CustomEvent('followStatusChanged'))
    } catch (error) {
        ElMessage.error(error.message || '取消关注失败')
    } finally {
        followLoading.value = false
    }
}

// 发送消息
const handleSendMessage = () => {
    router.push(`/chat?to=${userId.value}`)
}

// 跳转到关注/粉丝列表
const goToFollowList = (type) => {
    router.push(`/follow-list/${userId.value}?type=${type}`)
}

// 查看图片
const viewImage = (images, index) => {
    previewImages.value = images
    previewImageIndex.value = index
    imagePreviewVisible.value = true

    // 确保轮播图正确显示当前图片
    nextTick(() => {
        if (carouselRef.value) {
            carouselRef.value.setActiveItem(index)
        }
    })
}

// 关闭图片预览
const closeImagePreview = () => {
    imagePreviewVisible.value = false
    previewImages.value = []
    previewImageIndex.value = 0
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return ''
    const date = new Date(timeString)
    const now = new Date()
    const diffInSeconds = Math.floor((now - date) / 1000)

    if (diffInSeconds < 60) return `${diffInSeconds}秒前`
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`
    return `${Math.floor(diffInSeconds / 86400)}天前`
}

// 格式化日期
const formatDate = (timeString) => {
    if (!timeString) return ''
    return new Date(timeString).toLocaleDateString()
}

// 监听关注状态变化
const handleFollowStatusChange = () => {
    loadStats()
}

onMounted(() => {
    fetchUserDetail()
    fetchUserPosts()

    // 添加事件监听，参考UserStatsCard.vue
    window.addEventListener('followStatusChanged', handleFollowStatusChange)
})

// 清理事件监听
import { onUnmounted } from 'vue'
onUnmounted(() => {
    window.removeEventListener('followStatusChanged', handleFollowStatusChange)
})
</script>

<style scoped>
.user-detail-page {
    min-height: 100vh;
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
}

.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.user-detail-main {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    margin-left: 280px;
}

.user-detail-container {
    max-width: 1000px;
    margin: 0 auto;
}

.user-profile-card {
    margin-bottom: 20px;
}

.profile-header {
    display: flex;
    gap: 30px;
    margin-bottom: 30px;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
}

.user-avatar img {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid #e4e7ed;
}

.avatar-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: center;
}

.profile-info {
    flex: 1;
}

.username {
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #303133;
}

.user-meta {
    display: flex;
    gap: 16px;
    margin-bottom: 12px;
    font-size: 14px;
    color: #666;
}

.user-meta span {
    display: flex;
    align-items: center;
    gap: 4px;
}

.bio {
    font-size: 16px;
    color: #606266;
    margin-bottom: 20px;
    line-height: 1.5;
}

.profile-stats {
    display: flex;
    gap: 30px;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    transition: color 0.3s;
}

.stat-item:hover {
    color: #409eff;
}

.stat-number {
    font-size: 20px;
    font-weight: bold;
    color: #303133;
}

.stat-label {
    font-size: 14px;
    color: #909399;
}

.profile-details {
    margin-top: 20px;
}

.user-posts-card {
    margin-bottom: 20px;
}

.card-header {
    font-size: 18px;
    font-weight: bold;
}

.posts-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.post-item {
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    transition: box-shadow 0.3s;
}

.post-item:hover {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.post-content {
    margin-bottom: 12px;
    line-height: 1.6;
    color: #303133;
}

/* 动态图片样式 */
.post-images {
    margin: 12px 0;
    width: 400px;
}

.images-grid {
    display: grid;
    gap: 8px;
}

.images-1 {
    grid-template-columns: 1fr;
}

.images-2 {
    grid-template-columns: 1fr 1fr;
}

.images-3 {
    grid-template-columns: 1fr 1fr;
}

.images-4 {
    grid-template-columns: 1fr 1fr;
}

.image-item {
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.3s;
}

.image-item:hover {
    transform: scale(1.02);
}

.image-item img {
    width: 100%;
    height: 200px;
    object-fit: cover;
    display: block;
}

/* 图片预览样式 */
.image-preview {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.preview-carousel {
    width: 100%;
    height: 80vh;
}

.carousel-image {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.image-preview {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.preview-carousel {
    width: 100%;
    height: 100%;
}

.carousel-image {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.carousel-image img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

.post-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #909399;
    margin-top: 12px;
}

.post-stats {
    display: flex;
    gap: 15px;
    align-items: center;
}

.post-stats .el-icon {
    margin-right: 4px;
}

.empty-posts {
    text-align: center;
    padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .user-detail-main {
        margin-left: 240px;
        padding: 16px;
    }

    .profile-header {
        flex-direction: column;
        text-align: center;
    }

    .profile-stats {
        justify-content: center;
    }

    .post-meta {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
    }

    .images-grid {
        grid-template-columns: 1fr !important;
    }

    .image-item img {
        height: 150px;
    }
}
</style>